iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
自我挑戰組

利用 node.js/express 架設網站系列 第 4

Day-04 express練習(上)

  • 分享至 

  • xImage
  •  

今天要來練習使用express

創建基本的 Express 應用:

首先,要先創建一個app.js文件,並打上下列程式:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

執行後,就可以看到瀏覽器上出現"Hello express"
https://ithelp.ithome.com.tw/upload/images/20240918/20169465WDV4FF7rN0.png

設置路由

基本路由

  • GET路由
  • GET請求通常用於從伺服器獲取數據或顯示網頁內容。我們可以使用app.get()來處理GET請求。
app.get('/path', (req, res) => {
    // 處理請求並發送回應
});

範例:

app.get('/', (req, res) => {
    res.send('Welcome to the Homepage!');
});

app.get('/about', (req, res) => {
    res.send('This is the About page.');
});

https://ithelp.ithome.com.tw/upload/images/20240918/20169465nmXo47319a.pnghttps://ithelp.ithome.com.tw/upload/images/20240918/20169465Hfst3SIPGW.png
可以看到"/"和"/about"有著不同的頁面

使用路由參數

  • 路由參數允許你在 URL 中包含動態部分,這對於處理特定資源(例如用戶或產品)非常有用。在路由定義中,你可以使用冒號 : 來表示參數。
app.get('/route/:parameter', (req, res) => {
    // 使用 req.params.parameter 來獲取參數值
});

範例:

app.get('/user/:id', (req, res) => {
    const userId = req.params.id;
    res.send(`User ID: ${userId}`);
});

https://ithelp.ithome.com.tw/upload/images/20240918/20169465NBCdXUc6nq.png
可以看到當我訪問/user/234的時候,伺服器就會回應我"User ID: 234"

處理查詢字符串

  • 查詢字符串位於 URL 的 ? 後面,用於向伺服器傳遞額外的數據。你可以使用 req.query 來獲取查詢字符串中的參數。
app.get('/route', (req, res) => {
    // 使用 req.query.parameter 來獲取查詢字符串參數
});

範例:

app.get('/search', (req, res) => {
    const searchQuery = req.query.q;
    res.send(`Search query: ${searchQuery}`);
});

https://ithelp.ithome.com.tw/upload/images/20240918/20169465SQ4ikAJ9k1.png
只要我訪問/search?q=express,伺服器就會回應:“Search query: express”

處理不同的 HTTP 方法

  • 除了 GET 以外,Express 還可以處理其他的 HTTP 方法,如 POST、PUT、DELETE 等。這對於構建 RESTful API 非常有用。

  • POST 請求:
    通常用於向伺服器發送數據,例如提交表單。

app.post('/route', (req, res) => {
    // 處理 POST 請求
});

範例:

app.post('/submit', (req, res) => {
    const formData = req.body; // 需要使用中介軟體來解析請求體
    res.send(`Received data: ${JSON.stringify(formData)}`);
});

這個範例會需要使用中介軟體(例:express.json())來解析請求體(明天會學到什麼是中介軟體)

  • PUT 和 DELETE 請求:
    用於更新或刪除伺服器上的資源。
    範例:
app.put('/user/:id', (req, res) => {
    const userId = req.params.id;
    // 更新用戶數據
    res.send(`User ${userId} updated`);
});

app.delete('/user/:id', (req, res) => {
    const userId = req.params.id;
    // 刪除用戶
    res.send(`User ${userId} deleted`);
});

使用 Router 進行路由分離

當應用程式變得複雜時,可以使用 express.Router 來分離和組織路由,這樣可以讓程式更清晰、更易於維護。

  • 創建路由模組:
    首先需要在routes目錄中創建一個users.js的文件
    https://ithelp.ithome.com.tw/upload/images/20240918/201694650sLnQ4EKOJ.png
    並且在主文件中導入這個文件並使用這個路由
const usersRouter = require('./routes/users');

這麼一來就可以將特定的頁面分類至資料夾,讓程式更容易維護

  • 路由中間件:
    你可以在特定的路由中使用中間件來執行一些預處理,例如驗證或日誌記錄。
    範例:
const logger = (req, res, next) => {
    console.log(`Request Method: ${req.method}, URL: ${req.url}`);
    next();
};

app.get('/profile', logger, (req, res) => {
    res.send('User Profile');
});

這樣在訪問/profile時,中間的logger會先被調用。


上一篇
Day-03 node.js核心模組
下一篇
Day-05 express練習(下)
系列文
利用 node.js/express 架設網站26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言